package my.controller;

//import com.baidu.ueditor.*;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.JMap;
import com.jfinal.kit.JsonKit;
import my.interceptor.CategoryMenuInterceptor;
import my.interceptor.Login;
import my.model.User;
import my.service.CategoryService;
import my.service.UserService;

/**
 * Created by Rajab on 2017/03/30.
 */
public class MainController extends Controller {

    private static UserService userService = new UserService();
    private static CategoryService categoryService = new CategoryService();

    @Before(CategoryMenuInterceptor.class)
    public void index() {
        main();
    }

    public void login() {
        String redirectUrl = null;
        if (getPara("redirectUrl") != null) {
            redirectUrl = getPara("redirectUrl");
        } else if (getRequest().getHeader("Referer") != null) {
            String referer = getRequest().getHeader("Referer").toString();
            redirectUrl = (referer != null && !referer.contains("login")) ? referer : getRequest().getContextPath().toString();

        }
        if (redirectUrl != null) {
            setAttr("redirectUrl", redirectUrl);
        }

        renderFreeMarker("login.ftl");
    }

    public void loginCheck() {
        String username = getPara("username", "");
        String password = getPara("password", "");
        String redirectUrl = getPara("redirectUrl", getRequest().getContextPath().toString());


        UserService.LoginResult result = userService.checkLogin(username, password);
        boolean success = false;
        switch (result) {
            case LOGIN_OK:
                User user = userService.findUserByUsername(username);
                if (user != null)
                    setSessionAttr("user", user);
                success = true;
                setAttr("redirectUrl", redirectUrl);
                setAttr("message", "登录成功");
                break;
            case INPUT_INVALID:
                setAttr("message", "用户名或密码为空");
                forwardAction("/login");
                break;
            case PASSWORD_WRONG:
                setAttr("message", "用户名或密码错误");
                break;
        }
        setAttr("success", success);
        renderJson();
    }

    @Before(Login.class)
    public void success() {
        renderFreeMarker("success.ftl");
    }

    @Before(CategoryMenuInterceptor.class)
    public void main() {
        renderFreeMarker("main.ftl");
    }

    public void logout() {
        //TODO:退出登录
        //提示 (1)使用removeSessionAttr(key)方法从Session中移除登录的username
        //(2)使用 redicrect(url)方法跳转到登录页面
        if (getSessionAttr("user") != null)
            removeSessionAttr("user");
        redirect("/login");

    }

    public void register() {
        //TODO:理解register-ref.ftl页面后  选择renderFreeMarker("register.ftl");
        // 提示：该页面期望获得json格式的注册结果 renderJson()
        renderFreeMarker("register.ftl");
    }

    @Before(POST.class)
    public void doregister() {

        String username = getPara("username", "");
        String password = getPara("password", "");
        String nickname = getPara("nickname", username);
        String message = "";
        boolean success = false;
        if (!username.isEmpty() && !password.isEmpty()) {
            UserService.RegisterResult result = userService.register(username, password, nickname);

            switch (result) {
                case REGISTER_OK:
                    success = true;
                    message = "注册成功";
                    break;
                case REGISTER_FAIL:
                    message = "注册失败";
                    break;
                case USER_IS_EXISTED:
                    message = "用户名存在";
                    break;
            }
        }

        // TODO: 注册显示的是register-ref.ftl
        //需要使用renderJson()方法 返回json数据 格式为:
        // ｛success : true或false, message : 返回的消息}

        setAttr("success", success);
        setAttr("message", message);
        //renderFreeMarker("register-result.ftl");
        renderJson();

    }


    public void imageup() {
//        /*SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmsss");
//        fmt.format(new Date());*/
//        JMap result = JMap.create();
//        try {
//            UploadFile uploadFile = getFile("upfile");
//            result.set("name", uploadFile.getFileName());
//            result.set("originalName", uploadFile.getOriginalFileName());
//            result.set("state", "SUCCESS");
//            result.set("type", "." + FilenameUtils.getExtension(uploadFile.getFileName()));
//
//
//            result.set("url", getRequest().getContextPath() + "/upload/" + uploadFile.getFileName());
//        } catch (Exception ex) {
//            result.set("state", "上传错误");
//        }

        JMap result = JMap.create();


  /*      Uploader uploader = new Uploader(getRequest());
        uploader.setSavePath("/upload");
        uploader.setAllowFiles(new String[]{".jpg", ".png", ".gif", ".jpeg", ".bmp"});
        try {
            uploader.upload();
            result.set("name", uploader.getFileName());
            result.set("originalName", uploader.getOriginalName());
            result.set("state", uploader.getState());
            result.set("type", uploader.getType());
            result.set("url", uploader.getUrl());

        } catch (Exception e) {

        }*/
        renderHtml(JsonKit.toJson(result));


    }

}
